package com.sikaryofficial.qrcode.controller;

import cn.hutool.core.collection.CollUtil;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.qrcode.config.ProductQrUrlConfig;
import com.sikaryofficial.qrcode.domain.entity.BrandTaste;
import com.sikaryofficial.qrcode.manager.ProductManager;
import com.sikaryofficial.qrcode.service.IBrandTasteService;
import com.sikaryofficial.system.api.model.qrcode.ProductQRReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

import static com.sikaryofficial.common.core.constant.CacheBusinessConstants.PRODUCT_QRCODE_STATUS_PREFIX;

/**
 * @author qinjinyuan
 * @description 产品二维码生成服务
 * @date 2023-07-18 21:38
 **/
@Api(tags = "二维码生成服务")
@RestController
@RequestMapping("/core")
@Slf4j
public class QrCoreController {
    @Resource(name = "asyncTaskExecutor")
    private ThreadPoolTaskExecutor asyncTaskExecutor;
    @Autowired
    private ProductManager productManager;
    @Autowired
    private IBrandTasteService brandTasteService;
    @Autowired
    private ProductQrUrlConfig config;
    @Autowired
    private RedisService redisService;

    @PostMapping("/qrCodeGen")
    @ApiOperation(value = "生成商品二维码")
    public R<String> productQRGen(@Validated @RequestBody ProductQRReq req) {
        if (Objects.isNull(req.getQrNum()) || req.getQrNum() <= 0 || req.getQrNum() > config.getProductQRMax()) {
            throw new ServiceException("the input qrNum is empty | zero | bigger then " + config.getProductQRMax());
        }
        try {
            // 判定当前是否有进行中的任务
            BrandTaste brandTaste = brandTasteService.getById(req.getBrandTasteId());
            if (Objects.isNull(brandTaste)) {
                throw new ServiceException("the product is not exist");
            }
            Collection<String> keyList = redisService.keys(PRODUCT_QRCODE_STATUS_PREFIX + "*");
            // 缓存key数量判定 & 并发3个线程进行生成
            if (CollUtil.isNotEmpty(keyList) && keyList.size() > 3) {
                throw new ServiceException("QrFile is generating, please wait ");
            } else {
                CompletableFuture.runAsync(() -> productManager.productQRGen(req), asyncTaskExecutor);
            }
        } catch (Exception e) {
            log.error("productQRDownload:{}", e);
            throw new ServiceException("productQRDownload error." + e.getMessage());
        }
        return R.ok("success");
    }
}
